package com.hzdl.goods.service.impl;

import com.hzdl.goods.entity.Goods;
import com.hzdl.goods.repository.GoodsRepository;
import com.hzdl.goods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsRepository goodsRepository;

    @PostConstruct
    @Transactional
    public void init() {
        // 检查是否已有数据
        if (goodsRepository.count() == 0) {
            // 创建测试数据
            Goods goods1 = new Goods();
            goods1.setName("iPhone");
            goods1.setPrice(5999);
            goods1.setStock(100);
            
            Goods goods2 = new Goods();
            goods2.setName("MacBook");
            goods2.setPrice(9999);
            goods2.setStock(50);
            
            Goods goods3 = new Goods();
            goods3.setName("iPad");
            goods3.setPrice(3999);
            goods3.setStock(200);
            
            // 保存测试数据
            goodsRepository.saveAll(Arrays.asList(goods1, goods2, goods3));
        }
    }

    @Override
    public List<Goods> findAll() {
        return goodsRepository.findAll();
    }

    @Override
    public Optional<Goods> findById(Long id) {
        return goodsRepository.findById(id);
    }
}
